package com.bawei.module_publish.ui

import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.Settings
import android.view.View
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_common.base.BaseApplication
import com.bawei.lib_mvi.Router
import com.bawei.lib_mvi.base.BaseMVIActivity
import com.bawei.module_publish.R
import com.bawei.module_publish.adapter.ToolsListAdapter
import com.bawei.module_publish.databinding.ActivityPublishBinding
import com.bawei.module_publish.model.ToolsModelItem
import com.bawei.module_publish.utils.PermissionChecker
import com.blankj.utilcode.util.ToastUtils
import com.qiniu.pili.droid.shortvideo.PLAuthenticationResultCallback
import com.qiniu.pili.droid.shortvideo.PLShortVideoEnv
import java.text.SimpleDateFormat
import java.util.Locale


@Route(path = Router.Ui.PUBLISH_Actvivty)
class PublishActivity : BaseMVIActivity() {

    private val binding: ActivityPublishBinding by lazy {
        ActivityPublishBinding.inflate(layoutInflater)
    }
    private lateinit var mActivityResultLauncher: ActivityResultLauncher<Intent>

    private val toolsList = mutableListOf<ToolsModelItem>()

    private lateinit var mAdapter: ToolsListAdapter

    override fun generateViewModel() {

    }


    override fun getLayoutRootView(): View {
        return binding.root
    }

    override fun handleState() {

    }

    override fun initEnv() {
        PLShortVideoEnv.checkAuthentication(
            applicationContext
        ) { result ->
            if (result == PLAuthenticationResultCallback.UnCheck) {
                ToastUtils.showLong("UnCheck")
            } else if (result == PLAuthenticationResultCallback.UnAuthorized) {
                ToastUtils.showLong("UnAuthorized")
            } else {
                ToastUtils.showLong("Authorized")
            }
        }

        mActivityResultLauncher = registerForActivityResult<Intent, ActivityResult>(
            ActivityResultContracts.StartActivityForResult()
        ) { result: ActivityResult ->
            if (result.resultCode != RESULT_OK || result.data == null) {
                ToastUtils.showLong("未获得全局存储权限")
            }
        }

        binding.lUpload.setOnClickListener {
        }

    }


    override fun initView() {
        super.initView()
        toolsList.add(ToolsModelItem(R.mipmap.ic_move_editor, "视频剪辑"))
        toolsList.add(ToolsModelItem(R.mipmap.ic_music, "视频录制"))
        toolsList.add(ToolsModelItem(R.mipmap.ic_mode, "创作模版"))
        toolsList.add(ToolsModelItem(R.mipmap.ic_menu, "免费素材"))
        toolsList.add(ToolsModelItem(R.mipmap.ic_tools, "工具箱"))
    }

    override fun initData() {
        super.initData()
        mAdapter = ToolsListAdapter(toolsList) { position ->
            val item = toolsList[position]
            if (item.subTitle == "视频剪辑") {
                ARouter.getInstance().build("/publish/VideoTrimActivity").navigation()
            }else if (item.subTitle == "视频录制") {
                ARouter.getInstance().build("/publish/VideoRecordActivity").navigation()
            }
            // 其他功能可按需添加
        }
        binding.rvPublishTools.adapter = mAdapter
        binding.rvPublishTools.layoutManager = GridLayoutManager(this, 4)
    }

    override fun initEvent() {

        binding.shootingContainer.setOnClickListener {
            ToastUtils.showLong("点击了拍摄按钮")

            // 原来的权限检查逻辑
            if (isPermissionOK()) {
                ARouter.getInstance().build(Router.Ui.OPEN_LIVE_ACTIVITY).navigation()
            }
        }

        binding.tvDrafts.setOnClickListener {
            ARouter.getInstance().build("/publish/DraftActivity").navigation()
        }

        binding.ivClose.setOnClickListener {
            finish()
        }

    }


    private fun isPermissionOK(): Boolean {
        val checker: PermissionChecker = PermissionChecker(this)
        val isPermissionOK =
            Build.VERSION.SDK_INT < Build.VERSION_CODES.M || checker.checkPermission()
        if (!isPermissionOK) {
            ToastUtils.showLong("Some permissions is not approved !!!")
        }
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q && !Environment.isExternalStorageManager()) {
            try {
                val intent = Intent()
                intent.setAction(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
                val uri = Uri.fromParts("package", packageName, null)
                intent.setData(uri)
                mActivityResultLauncher.launch(intent)
            } catch (exception: Exception) {
                exception.printStackTrace()
            }
            return false
        }
        return isPermissionOK
    }


    private fun getVersionDescription(): String {
        val packageManager = packageManager
        try {
            val packageInfo = packageManager.getPackageInfo(packageName, 0)
            return packageInfo.versionName
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }
        return "未知"
    }

    protected fun getBuildTimeDescription(): String {
        return SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss",
            Locale.CHINA
        ).format(1751248843552L)
    }
}